package com.kbbywyclient.presenter;

import android.content.Context;

import com.kbbywyclient.data.entity.ApplicationRecordData;
import com.kbbywyclient.data.model.ApplicationRecordModel;
import com.kbbywyclient.presenter.base.BasePresenter;
import com.kbbywyclient.service.ApiService;
import com.kbbywyclient.service.ApiServiceHelper;
import com.kbbywyclient.ui.contarct.ApplicationRecordContract;
import com.kbbywyclient.util.HttpExcUtil;
import com.kbbywyclient.util.RsaJsonUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/15 11:10.
 */

public class ApplicationRecordPresenter extends BasePresenter implements ApplicationRecordContract.Presenter {
    public static final int PAGE_START=1;
    @Inject
    Context mContext;
    @Inject
    ApiService apiService;
    @Inject
    RsaJsonUtil jsonUtil;

    public int mBankId=-1;
    public int mPage=PAGE_START;

    private ApplicationRecordContract.View view;

    private List<ApplicationRecordData.Record> mData;


    @Inject
    public ApplicationRecordPresenter(ApplicationRecordContract.View view){
        this.view=view;
        this.mData=new ArrayList<>();
    }

    @Override
    public void loadRecords(int salesId, int bankId, int pageNumber) {
        jsonUtil.put("pageNum",pageNumber);
        jsonUtil.put("sale_id",salesId);
        if(bankId!=-1){
            jsonUtil.put("company_id",bankId);
        }
        ApiServiceHelper.
                appointThreadNormal(apiService.getApplicationRecords(jsonUtil.getRsaParams())).
                subscribe(new Subscriber<ApplicationRecordModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mPage--;
                        if(mPage<PAGE_START){
                            mPage=PAGE_START;
                        }
                        HttpExcUtil.printError(e);
                        view.loadRecordComplete();
                    }

                    @Override
                    public void onNext(ApplicationRecordModel model) {
                        ApplicationRecordData data=model.getData();
                        if(data!=null){
                            view.loadDataBankSuccess(data.getBankList());
                            List<ApplicationRecordData.Record> records=data.getRecords();
                            if(records!=null&&records.size()>0){
                                mData.addAll(data.getRecords());
                            }
                        }
                        view.loadRecordComplete();
                        view.loadRecordsSuccess(mData,mPage<model.getTotalPage());
                    }
                });
    }

    @Override
    public void clearList() {
        mPage=PAGE_START;
        mData.clear();
    }
}
